<?php
namespace Logic\System;
use Spartan\Lib\Logic;

defined('APP_PATH') OR exit('404 Not Found');

class Verify extends Logic{

	//添加一个验证码
	public function add(){
		$arrData['user_id'] = $this->getData('user_id',0);//验证的用户ID
		$arrData['type'] = strtoupper($this->getData('send_type',''));//发送的类型
		if (!in_array($arrData['type'],['MOBILE','EMAIL'])) {//如果没有传入，就用默认的。
			return Array('发送类似只能为“MOBILE”，“EMAIL”。',0);
		}
		$arrData['rad_code'] = $this->getData('rad_code','');//是否定义了验证码
		!$arrData['rad_code'] && $arrData['rad_code'] = $this->_getCode();
		$arrData['send_to'] = $this->getData('send_to','');//发送的对像
		if ($arrData['type']=='MOBILE'){
			if (!isMobile($arrData['send_to'])){
				return Array('验证类型为手机，却不是手机。',0);
			}
		}elseif ($arrData['type']=='EMAIL'){
			if (!isEmail($arrData['send_to'])){
				return Array('验证类型为邮箱，却不是邮箱。',0);
			}
		}
		$arrData['valid_time'] = $this->getData('valid_time',0);//验证码有效期
		if (!$arrData['valid_time']){//如果没有传入，就用默认的。
			unset($arrData['valid_time']);
		}
		$arrData['tpl_key'] = $this->getData('tpl_key','');//发送的模版
		if (!$arrData['tpl_key']){
			return Array('发送模版KEY不能为空。',0);
		}
		$arrData['add_time'] = date('Y-m-d H:i:s',time());
		$arrData['ip'] = $this->getData('_ip_','');
		$arrData['type'] = $arrData['type']=='MOBILE'?2:1;//1邮件，2手机
		$result = $this->Db()->insert('system_verify',$arrData);
		$arrData['type'] = $arrData['type']==2?'MOBILE':'EMAIL';//1邮件，2手机
		$arrData['id'] = max(0,$result);
		return Array('success',1,$arrData);
	}

	//验证一个验证码
	public function verify(){
		$options = Array();
		$strVerifyTip = $this->getData('verify_tip','');
		$this->getData('id',0) > 0 && $options['where']['id'] = $this->getData('id',0);
		$this->getData('user_id',0) > 0 && $options['where']['user_id'] = $this->getData('user_id',0);
		$this->getData('rad_code','') && $options['where']['rad_code'] = strtolower(trim($this->getData('rad_code','')));
		$this->getData('send_to','') && $options['where']['send_to'] = $this->getData('send_to','');
		$this->getData('tpl_key','') && $options['where']['tpl_key'] = $this->getData('tpl_key','');
		if (!isset($options['where']['rad_code'])){
			return Array($strVerifyTip.'验证码丢失。',0,[]);
		}
		if (!isset($options['where']['send_to'])&&!isset($options['where']['id'])&&!isset($options['where']['user_id'])){//发送对像和验证的ID，至少需要一个
			return Array('接受者或用户ID或该验证的ID丢失。',0,[]);
		}
		if (!isset($options['where']['tpl_key'])){
			return Array($strVerifyTip.'验证模块KEY丢失。',0,[]);
		}
		$arrInfo = $this->Db()->find('system_verify',$options);
		if (!$arrInfo){
           return array($strVerifyTip.'验证码不正确，请确认。',0,[]);
		}
		if ($arrInfo['status'] != 1){
			return Array($strVerifyTip.'验证码错误，请重新输入', 0, []);
		}
		if ($this->getData('valid_time',0)){//如果传了需要验证时间，就验证
			if (strtotime($arrInfo['add_time']) + $arrInfo['valid_time'] * 60 < time()){
				return Array($strVerifyTip."验证码已经超过有效期，请在{$arrInfo['valid_time']}分钟之内使用。", 0 ,[]);
			}
		}
		//把验证码的ID压入getData，用于处理过期。
		$this->setData(Array('verify_id'=>$arrInfo['id']));
        $arrInfo['verify_id'] = $arrInfo['id'];
		return Array($this->Db()->getLastSql(),1,$arrInfo);
	}
	//**把验证码失效。
	//更新条件为getDate里的verify_id
	public function invalid(){
		$intId = max(0,$this->getData('verify_id',0));
		if ($intId < 1){
			return Array('ID无效。',0);
		}
		$options = Array(
			'where'=>Array('id'=>$intId),
		);
		$arrData = Array(
			'active_time'=> date('Y-m-d H:i:s',time()),
		    'status'=>2,//2为已使用
		);
		$result = $this->Db()->update('system_verify',$arrData,$options);
		//作费同一类验证码
		$arrInfo = $this->Db()->find('system_verify',$options);
		if ($arrInfo){
			$options = Array(
				'where'=>Array(
					'type'=>$arrInfo['type'],
					'send_to'=>$arrInfo['send_to'],
					'tpl_key'=>$arrInfo['tpl_key'],
					'status'=>1,//只把未更新的弄掉
				),
			);
			$arrData['active_time'] = 0;
			$result = $this->Db()->update('system_verify',$arrData,$options);
		}
		return Array('更改验证码状态成功',$result===false?0:1,$this->Db()->getLastSql());
	}

	/**
	 * @return string 返回验证码串串。
	 */
	private function _getCode(){
		$strTplKey = strtolower($this->getData('tpl_key'));
		$strType = strtoupper($this->getData('send_type',''));
		$strCode = '';
		if ($strType == 'MOBILE' || $strType == 'EMAIL'){
			for ($i = 0;$i < 6; $i++){
				$strCode .= chr(mt_rand(48, 57));
			}
		}elseif ($strType == 'EMAIL'){
			if (in_array($strTplKey,['lost_password','reset_payword','reset_password','bind_email','reg_activate','user_activate'])){
				for ($i = 0; $i < 8; $i++){
					$strCode .= chr(mt_rand(48, 90));
				}
				$strCode = preg_replace('/[^\w]/','A',$strCode);
			}else{
				for ($i = 0; $i < 10; $i++){
					$strCode .= chr(mt_rand(97, 122));
				}
				$strCode = md5($strCode);
			}
		}
		return strtolower($strCode);
	}


} 